package com.young.springdemo.service.expression;

import java.util.Stack;

//指令处理类
public class InstructionHandler {

    private AbstractExpression node;

    public void handle(String instructions) {
        Stack<AbstractExpression> stack = new Stack<>();
        String[] words = instructions.split(" ");
        //up move 2 and down run 10
        for (int i = 0; i < words.length; i++) {
            if (words[i].equalsIgnoreCase("and")) {
                //and 拼接 AndNode
                AbstractExpression left = stack.pop();
                DirectionNode directionNode = new DirectionNode(words[++i]);
                ActionNode actionNode = new ActionNode(words[++i]);
                DistanceNode distanceNode = new DistanceNode(words[++i]);
                SentenceNode sentenceNode = new SentenceNode(directionNode, actionNode, distanceNode);
                AndNode andNode = new AndNode(left, sentenceNode);
                stack.push(andNode);
            } else {
                //直接拼接left
                DirectionNode directionNode = new DirectionNode(words[i]);
                ActionNode actionNode = new ActionNode(words[++i]);
                DistanceNode distanceNode = new DistanceNode(words[++i]);
                SentenceNode sentenceNode = new SentenceNode(directionNode, actionNode, distanceNode);
                stack.push(sentenceNode);
            }
        }
        this.node = stack.pop();
    }


    public String outPut() {
        return node.interrupt();
    }
}
